﻿using System.Threading.Tasks;

namespace Sidvall.WorkItemManager.Workflow
{
    public class WorkManager
    {
        #region Public Members

        public ServerManager ServerManager { get; set; }

        #region ExecuteAsync

        public async Task ExecuteAsync(WorkItemContext context)
        {
            if (context == null)
                throw new System.Exception("You have to specify a context.");
            if ((context.WorkerIds == null) || (context.WorkerIds.Length == 0))
                throw new System.Exception("You have to specify a worker.");
            await ExecuteAsync(context.WorkerIds, context.CleanLog, context.IsTestRun).ConfigureAwait(false);
        }
        public async Task ExecuteAsync(long[] workerIds, bool cleanLog, bool skipActions)
        {
            if (workerIds == null)
                return;
            if (workerIds.Length == 0)
                return;
            foreach (var workerId in workerIds)
            {
                var workManagerTask = WorkManagerTask.GetWorkManagerTask(this.ServerManager, cleanLog, skipActions, workerId);
                await workManagerTask.ExecuteAsync().ConfigureAwait(false);
            }
        }

        #endregion

        #endregion
        #region Factory Members

        #region GetWorkManagerAsync

        public static async Task<WorkManager> GetWorkManagerAsync(int? serverConnectionId)
        {
            var item = new WorkManager();
            item.ServerManager = await ServerManagerFactory.GetServerManagerAsync(serverConnectionId).ConfigureAwait(false);
            return item;
        }

        #endregion

        #endregion
        #region Constructors

        private WorkManager()
        {
        }

        #endregion
    }
}
